package com.alon.spring01.common.config.pool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @program: spring01
 * @description: 配置线程池初始化bean
 * @author: yulongguang
 * @create: 2019-04-12 11:10
 **/
@Configuration
@EnableAsync
@EnableConfigurationProperties({TaskThreadPoolProperties.class})
public class TaskThreadPoolConfig {

    @Autowired
    private TaskThreadPoolProperties poolProperties;

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(poolProperties.getCorePoolSize());
        // 设置最大线程数
        executor.setMaxPoolSize(poolProperties.getMaxPoolSize());
        // 设置队列容量
        executor.setQueueCapacity(poolProperties.getQueueCapacity());
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(poolProperties.getKeepAliveSeconds());
        // 设置默认线程名称
        executor.setThreadNamePrefix(poolProperties.getNamePrefix());
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;

    }

}
